package com.hsnn.medstgmini.base.dict.dao.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.hsnn.medstgmini.base.dict.dao.DicDrugmaterialLogDao;
import com.hsnn.medstgmini.base.dict.model.DicDrugmaterialLog;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.util.Pagination;

/**
 * 基础库 数据字典 材质字典 接口 实现类
 * @author hss@njhsnn
 * 2015年6月9日
 */
@Repository
public class DicDrugmaterialLogDaoImpl extends BaseHibernateDAO implements DicDrugmaterialLogDao {
	
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	
	@Autowired
	private HibernateSqlUtil sqlUtil;


	/**
	 *  基础库 数据字典 材质字典 维护记录添加
	 * @param dicDrugmaterialLog
	 */
	@Transactional
	@Override
	public void add(DicDrugmaterialLog dicDrugmaterialLog) {
		this.getSession().saveOrUpdate(dicDrugmaterialLog);
		getSession().flush();
		getSession().clear();
	}

	/**
	 * 基础库 数据字典 材质字典 维护记录查询所有及条件查询
	 * @param result ,dicDrugmaterialLog
	 * @return
	 */
	@Override
	public Pagination queryDicDrugmaterialLogByName(
			Pagination page) {
		String materialId = page.getConditions().get("materialId");
		String date1 = page.getConditions().get("date1");
		String date2 = page.getConditions().get("date2");
		StringBuffer sql = new StringBuffer();
		StringBuffer sqlCount = new StringBuffer();
		sql.append("  SELECT 1,d.detail,d.material_code,d.material_name,  ")
		   .append("  d.status,s.name,DATE_FORMAT(d.upd_datetime,'%Y-%m-%d %H:%i:%S'),d.log_id logId      ")
		   .append("  FROM  dic_drugmaterial_log d             ")
		   .append("  LEFT JOIN  sys_user s ON s.id=d.upd_user ")
		   .append("  WHERE d.material_id =:materialId         ");
		sqlCount.append("  SELECT count(*)                          ")
		        .append("  FROM  dic_drugmaterial_log d             ")
		        .append("  LEFT JOIN  sys_user s ON s.id=d.upd_user ")
		        .append("  WHERE d.material_id =:materialId         ");
		if(StringUtils.isNotBlank(date1)){
			sql.append(" and d.upd_datetime>= :date1 ");
			sqlCount.append(" and d.upd_datetime>= :date1 ");
		}
		if(StringUtils.isNotBlank(date2)){
			sql.append(" and d.upd_datetime<= :date2 ");
			sqlCount.append(" and d.upd_datetime<= :date2 ");
		}
		sql.append(" order by d.upd_datetime desc ");
		Query query  = getSession().createSQLQuery(sql.toString());
		Query queryCount  = getSession().createSQLQuery(sqlCount.toString());
		query.setString("materialId", materialId);
		queryCount.setString("materialId", materialId);
		if(StringUtils.isNotBlank(date1)){
			query.setString("date1", date1+" 00:00:00");
			queryCount.setString("date1", date1+" 00:00:00");
		}
		if(StringUtils.isNotBlank(date2)){
			query.setString("date2", date2+" 23:59:59");
			queryCount.setString("date2", date2+" 23:59:59");
		}
		page.setRecords(Long.parseLong(queryCount.uniqueResult().toString()));
		query.setFirstResult(page.getFirstResult());
		query.setMaxResults(page.getMaxResults());
		page.setRows(query.list());
		return page;
	}
	

	/**
	 * 
	 *@category 材质字典维护记录详情页面
	 *@author 言科
	 *@date 2015年9月11日
	 *String
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getDicDrugmaterialLogListDetail(Pagination page) {
		Session session = sessionFactory.getCurrentSession();
		String logId = page.getConditions().get("logId");
		StringBuffer  sql = new StringBuffer();
		sql.append(" select a.material_id materialId,a.material_code materialCode,a.material_name materialName,   ")
		   .append(" a.status status,date_format(a.upd_datetime,'%Y-%m-%d %T') updDatetime,b.name updUser  ")
		   .append(" from dic_drugmaterial_log a left join sys_user b on b.id=a.upd_user   ")
		   .append(" where a.material_id = (select material_id from dic_drugmaterial_log where log_id = :logId)    ")
		   .append("  and a.upd_datetime <= (select upd_datetime from dic_drugmaterial_log where log_id = :logId) ")
		   .append(" order by a.upd_datetime desc limit 2");
		Query query = session.createSQLQuery(sql.toString());
		query.setString("logId", logId);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return query.list();
	}

	
	
	
}
